<?php

namespace App\Http\Controllers\Teacher;

use App\Criteria\Teacher\Teacher\CertificateBaseQueryCriteria;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CurlRecordMethod;
use App\Http\Requests\Teacher\CertificateBaseRequest;
use App\Libs\Tools\UploadTools;
use App\Repositories\Teacher\CertificateRepository;
use App\Validators\Teacher\CertificateValidator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;


class CertificatesController extends Controller{

    use CurlRecordMethod;

    protected $index_page='teacher.certificate.certificateMain';
    protected $add_page='teacher.certificate.certificateAdd';
    protected $edit_page='teacher.certificate.certificateEdit';

    protected $repository;
    protected $validator;
    protected $request;

    public function __construct(CertificateRepository $repository, CertificateValidator $validator,CertificateBaseRequest $certificateBaseRequest)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
        $this->request    = $certificateBaseRequest;
    }

    public function getBaseQueryCriteria(){
        return new CertificateBaseQueryCriteria;
    }

    protected function get_add_data(){
        $teacher_id=Input::get('teacher_id');
        return view($this->add_page,compact('teacher_id'));
    }

    protected function post_add_data(){
        $all=$this->wrap_user_info($this->request->all(),true);
        try {
            $this->validator->with($all)->passesOrFail(ValidatorInterface::RULE_CREATE);
            $upload_file=$this->request->file('electron_attachment');
            $teacher_id=$this->request->get('teacher_id');
            $relativePath=UploadTools::generateUploadFileRelativePath($upload_file,'certificate/'.$teacher_id);
            $all['electron_attachment']=$relativePath;
            $this->repository->create($all);

            Storage::put($relativePath, file_get_contents($upload_file->getRealPath()));
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

}
